package jehc.djshi.workflow.web;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import jehc.djshi.common.annotation.AuthUneedLogin;
import jehc.djshi.common.entity.OauthAccountEntity;
import jehc.djshi.common.util.Base64Util;
import jehc.djshi.common.util.SortUtil;
import jehc.djshi.workflow.design.ImgXmlEntity;
import jehc.djshi.workflow.design.MxGraphToBase64;
import jehc.djshi.workflow.model.LcDeploymentHis;
import jehc.djshi.workflow.model.LcNodeAttribute;
import jehc.djshi.workflow.model.LcProcess;
import jehc.djshi.workflow.param.LcImgParam;
import jehc.djshi.workflow.param.NodeAttributeParam;
import jehc.djshi.workflow.service.LcDeploymentHisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jehc.djshi.common.annotation.NeedLoginUnAuth;
import jehc.djshi.common.base.BaseAction;
import jehc.djshi.common.base.BasePage;
import jehc.djshi.common.base.BaseResult;
import jehc.djshi.common.base.BaseSearch;
import jehc.djshi.common.util.StringUtil;
import jehc.djshi.workflow.service.LcNodeAttributeService;
import jehc.djshi.workflow.util.ActivitiUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.UserTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc 流程部署历史记录
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Api(value = "流程部署历史记录", description = "流程部署历史记录",tags = "流程部署历史记录")
@RestController
@RequestMapping("/lcDeploymentHis")
@Slf4j
public class LcDeploymentHisController extends BaseAction {
	@Autowired
	private LcDeploymentHisService lcDeploymentHisService;

	@Autowired
	ActivitiUtil activitiUtil;

	@Autowired
	private LcNodeAttributeService lcNodeAttributeService;

	/**
	 * 查询并分页
	 * @param baseSearch
	 * @return
	 */
	@ApiOperation(value="查询并分页", notes="查询并分页")
	@PostMapping(value="/list")
	@NeedLoginUnAuth
	public BasePage getLcDeploymentHisListByCondition(@RequestBody BaseSearch baseSearch){
		Map<String, Object> condition = baseSearch.convert();
		commonHPager(baseSearch);
		List<LcDeploymentHis> lcDeploymentHisList = lcDeploymentHisService.getLcDeploymentHisListByCondition(condition);
		for(LcDeploymentHis lcDeploymentHis:lcDeploymentHisList){
			if(!StringUtil.isEmpty(lcDeploymentHis.getCreate_id())){
				OauthAccountEntity createBy = getAccount(lcDeploymentHis.getCreate_id());
				if(null != createBy){
					lcDeploymentHis.setCreateBy(createBy.getName());
				}
			}
			if(!StringUtil.isEmpty(lcDeploymentHis.getUpdate_id())){
				OauthAccountEntity modifiedBy = getAccount(lcDeploymentHis.getUpdate_id());
				if(null != modifiedBy){
					lcDeploymentHis.setModifiedBy(modifiedBy.getName());
				}
			}
		}
		PageInfo<LcDeploymentHis> page = new PageInfo<LcDeploymentHis>(lcDeploymentHisList);
		return outPageStr(page,baseSearch);
	}
	/**
	* 查询单条记录
	* @param id
	*/
	@ApiOperation(value="查询单条记录", notes="查询单条记录")
	@GetMapping(value="/get/{id}")
	public BaseResult getLcDeploymentHisById(@PathVariable("id")String id){
		LcDeploymentHis lcDeploymentHis = lcDeploymentHisService.getLcDeploymentHisById(id);
		if(!StringUtil.isEmpty(lcDeploymentHis.getCreate_id())){
			OauthAccountEntity createBy = getAccount(lcDeploymentHis.getCreate_id());
			if(null != createBy){
				lcDeploymentHis.setCreateBy(createBy.getName());
			}
		}
		if(!StringUtil.isEmpty(lcDeploymentHis.getUpdate_id())){
			OauthAccountEntity modifiedBy = getAccount(lcDeploymentHis.getUpdate_id());
			if(null != modifiedBy){
				lcDeploymentHis.setModifiedBy(modifiedBy.getName());
			}
		}
		return outDataStr(lcDeploymentHis);
	}
	/**
	* 添加
	* @param lcDeploymentHis
	*/
	@ApiOperation(value="添加", notes="添加")
	@PostMapping(value="/add")
	public BaseResult addLcDeploymentHis(@RequestBody LcDeploymentHis lcDeploymentHis){
		int i = 0;
		if(null != lcDeploymentHis){
			lcDeploymentHis.setId(toUUID());
			i=lcDeploymentHisService.addLcDeploymentHis(lcDeploymentHis);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}

	/**
	* 修改
	* @param lcDeploymentHis
	*/
	@ApiOperation(value="修改", notes="修改")
	@PutMapping(value="/update")
	public BaseResult updateLcDeploymentHis(@RequestBody LcDeploymentHis lcDeploymentHis){
		int i = 0;
		if(null != lcDeploymentHis){
			i=lcDeploymentHisService.updateLcDeploymentHis(lcDeploymentHis);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}
	/**
	* 删除
	* @param id
	*/
	@ApiOperation(value="删除", notes="删除")
	@DeleteMapping(value="/delete")
	public BaseResult delLcDeploymentHis(String id,String flag){
		int i = 0;
		if(!StringUtil.isEmpty(id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id",id.split(","));
			condition.put("lc_deployment_his_status",flag);
			i=lcDeploymentHisService.delLcDeploymentHis(condition);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}

	/**
	 * 根据历史版本id查找设计器流程base64
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value="根据历史版本id查找设计器流程图", notes="根据历史版本id查找设计器流程base64")
	@GetMapping(value = "/image/base64/{id}")
	@AuthUneedLogin
	public BaseResult getImageBase64ByHisId(@PathVariable("id")String id, HttpServletRequest request, HttpServletResponse response){
		BaseResult baseResult = new BaseResult();
		try {
			LcDeploymentHis lcDeploymentHis = lcDeploymentHisService.getLcDeploymentHisById(id);
			if(null == lcDeploymentHis){
				log.info("未能查找到历史部署对象，id：{}",id);
				baseResult.setSuccess(false);
				baseResult.setMessage("未能查找到历史部署对象");
				return baseResult;
			}
			MxGraphToBase64 mxGraphToBase64 = new MxGraphToBase64();
			BufferedImage bufferedImage = mxGraphToBase64.imageXmlBase64(request.getRequestURI(),lcDeploymentHis.getImgxml(),lcDeploymentHis.getW(),lcDeploymentHis.getH(),response);
			String base64 = "data:image/png;base64," + Base64Util.toBase64(bufferedImage);
			baseResult.setData(base64);
		}catch (Exception e){
			log.error("查找到历史部署对象异常，{}",e);
		}
		return baseResult;
	}


	/**
	 * 根据历史版本id及节点属性查找设计器流程图
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value="根据历史版本id及节点属性查找设计器流程图", notes="根据历史版本id及节点属性查找设计器流程图")
	@PostMapping(value = "/image/attr/{id}")
	@AuthUneedLogin
	public BaseResult getActImgByByHisId(@PathVariable("id")String id, @RequestBody List<LcImgParam> lcImgParamList, HttpServletRequest request, HttpServletResponse response){
		BaseResult baseResult = new BaseResult();
		try {
			LcDeploymentHis lcDeploymentHis = lcDeploymentHisService.getLcDeploymentHisById(id);
			if(null == lcDeploymentHis){
				log.info("未能查找到历史部署对象，id：{}",id);
				baseResult.setSuccess(false);
				baseResult.setMessage("未能查找到历史部署对象");
				return baseResult;
			}
			List<String> idList = new ArrayList<>();
			if(!CollectionUtil.isEmpty(lcImgParamList)){
				for(LcImgParam lcImgParam: lcImgParamList){
					idList.add(lcImgParam.getActivityId());
				}
			}
			MxGraphToBase64 mxGraphToBase64 = new MxGraphToBase64();
			ImgXmlEntity imgXmlEntity = mxGraphToBase64.doImgXml(lcDeploymentHis.getImgxml(),idList);
			String xml = imgXmlEntity.getImgXml();
			BufferedImage bufferedImage = mxGraphToBase64.imageXmlBase64(request.getRequestURI(),xml,lcDeploymentHis.getW(),lcDeploymentHis.getH(),response);
			String base64 = "data:image/png;base64," +Base64Util.toBase64(bufferedImage);
			baseResult.setData(base64);
		}catch (Exception e){
			log.error("查找到历史部署版本对象异常，{}",e);
		}
		return baseResult;
	}

	/**
	 *
	 * @param nodeId
	 * @param hid_
	 * @return
	 */
	private LcNodeAttribute getLcNodeAttribute(String nodeId,String hid_){
		NodeAttributeParam nodeAttributeParam = new NodeAttributeParam();
		nodeAttributeParam.setNodeId(nodeId);
		nodeAttributeParam.setHid_(hid_);
		LcNodeAttribute lcNodeAttribute = lcNodeAttributeService.getLcNodeAttribute(nodeAttributeParam);
		return lcNodeAttribute;
	}

	/**
	 * 根据流程id查询任务节点集合
	 * @param id
	 * @return
	 */
	@ApiOperation(value="查询任务节点集合", notes="根据流程id查询任务节点集合")
	@PostMapping(value = "/userTasks/{id}")
	@AuthUneedLogin
	public BaseResult getTaskNodeList(@PathVariable("id")String id){
		List<LcNodeAttribute> lcNodeAttributes = new ArrayList<>();
		if(StringUtil.isEmpty(id)){
			return new BaseResult();
		}
		LcDeploymentHis lcDeploymentHis = lcDeploymentHisService.getLcDeploymentHisById(id);
		if(null != lcDeploymentHis){
			List<UserTask> userTasks = activitiUtil.getUserTaskElementsByBpmn(lcDeploymentHis.getLc_process_bpmn());
			for(UserTask userTask:userTasks){
				LcNodeAttribute lcNodeAttribute = new LcNodeAttribute();
				lcNodeAttribute.setNodeId(userTask.getId());
				lcNodeAttribute.setNodeName(userTask.getName());
				lcNodeAttribute.setLc_process_title(lcDeploymentHis.getLc_process_title());
				lcNodeAttribute.setLc_process_id(lcDeploymentHis.getLc_process_id());
				lcNodeAttribute.setHid_(lcDeploymentHis.getId());
				lcNodeAttribute.setNodeType(ActivitiUtil.USER_TASK);
				LcNodeAttribute nodeAttribute = getLcNodeAttribute(userTask.getId(),lcDeploymentHis.getId());
				if(null != nodeAttribute){
					lcNodeAttribute.setLc_node_attribute_id(nodeAttribute.getLc_node_attribute_id());
					lcNodeAttribute.setInitiator(nodeAttribute.getInitiator());
					lcNodeAttribute.setOrderNumber(nodeAttribute.getOrderNumber());
				}else{
					lcNodeAttribute.setOrderNumber(0);
				}
				if(activitiUtil.validateNodeIsMultiInstance(userTask)){
					lcNodeAttribute.setMutil("20");
				}else{
					lcNodeAttribute.setMutil("10");
				}
				lcNodeAttributes.add(lcNodeAttribute);
			}
			SortUtil.Sort(lcNodeAttributes, "orderNumber", "asc");
			List<EndEvent> endEvents = activitiUtil.getEventElementsByBpmn(lcDeploymentHis.getLc_process_bpmn());
			for(EndEvent endEvent : endEvents){
				LcNodeAttribute lcNodeAttribute = new LcNodeAttribute();
				lcNodeAttribute.setNodeId(endEvent.getId());
				lcNodeAttribute.setNodeName(endEvent.getName());
				lcNodeAttribute.setLc_process_title(lcDeploymentHis.getLc_process_title());
				lcNodeAttribute.setLc_process_id(lcDeploymentHis.getLc_process_id());
				lcNodeAttribute.setHid_(lcDeploymentHis.getId());
				lcNodeAttribute.setMutil("10");
				lcNodeAttribute.setNodeType(ActivitiUtil.END);
				lcNodeAttributes.add(lcNodeAttribute);
			}
			SortUtil.Sort(lcNodeAttributes, "orderNumber", "asc");
			return new BaseResult(lcNodeAttributes);
		}

		return new BaseResult(lcNodeAttributes);
	}

	/**
	 * 根据模块key查找唯一最新记录
	 * @param moduleKey
	 */
	@ApiOperation(value="根据模块key查找最新部署", notes="根据模块key查找唯一最新记录")
	@GetMapping(value="/deployment/{moduleKey}")
	public BaseResult getLcDeploymentHisByModuleKey(@PathVariable("moduleKey")String moduleKey){
		LcDeploymentHis lcDeploymentHis = lcDeploymentHisService.getLcDeploymentHisByModuleKey(moduleKey);
		return outDataStr(lcDeploymentHis);
	}
}
